package com.fjrcloud.aop;

import com.fjrcloud.service.TemplateService;
import com.fjrcloud.utils.ConfigInfo;
import com.fjrcloud.utils.StatusUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: Trun
 * Date: 2016-11-24
 * Description: HtmlIntercept.java
 */

@Aspect
@Component
@Order(20)
public class HtmlIntercept {

    @Autowired
    private ConfigInfo configInfo;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TemplateService templateService;


    private Model model(JoinPoint point) {
        Object[] arg = point.getArgs();
        for (Object obj : arg) {
            if (obj instanceof Model)
                return (Model) obj;
        }
        return null;
    }

    private void attribute(Model model, String name, Object value) {
        if (model == null)
            return;
        model.addAttribute(name, value);
    }


    @Before("execution(public * com.fjrcloud.controller..*.*(..))")
    public void before(JoinPoint point) throws Throwable {

        Model model = model(point);

        attribute(model, "path", request.getContextPath());
        attribute(model, "img_path", request.getContextPath());
        attribute(model, "file_path", request.getContextPath());
        attribute(model, "result_success", StatusUtils.Success.getCode());

        attribute(model, "user", request.getSession().getAttribute("user"));
        attribute(model, "user_type", request.getSession().getAttribute("user-type"));

    }
    @Before("execution(public * com.fjrcloud.controller.HtmlHouseholdController.*(..))")
    public void household(JoinPoint point) throws Throwable {

        Model model = model(point);

        attribute(model, "templates", templateService.list(null,null).getContent());
    }
    @Around("execution(public * com.fjrcloud.controller..*.*(..)) " +
            "&& !execution(public * com.fjrcloud.controller.HtmlHomeController.login(..))" +
            "&& !execution(public * com.fjrcloud.controller.UserController.login(..))")
    public Object login(ProceedingJoinPoint point) throws Throwable {

        Object type = request.getSession().getAttribute("user-type");

        if (type == null)
            return "redirect:/login";
        else
            return point.proceed();
    }

}
